<template id="carActionRequest-handle">
  <!-- 采购付款申请抽屉 -->
  <v-navigation-drawer v-if="isUpdateDrawerShown" v-model="isUpdateDrawerShown" :permanent="isUpdateDrawerShown" fixed
    temporary right width="80%" class="elevation-24">
    <v-form ref="createForm" lazy-validation>
      <!-- 抽屉标题 -->
      <v-row>
        <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">{{ticketType}}-处理</span>
        <v-spacer></v-spacer>
        <!-- 抽屉操作按钮 -->
        <v-row class="justify-end mx-0 mt-6 px-8" v-if="isAllowUpdate">
          <v-btn color="success" @click="doUiAction('updateItem')" small>提交</v-btn>
          <v-btn class="elevation-0 ml-2" @click="isUpdateDrawerShown = false" small>取消</v-btn>
        </v-row>
      </v-row>

      <!-- 抽屉内容 -->
      <v-expansion-panels accordion flat multiple v-model="expands">
        <v-expansion-panel v-for="ticket, index in ticketList" :key="index">
          <v-card class="mx-4 mb-4" outlined>
            <v-expansion-panel-header>{{`【${ticket.ticketContent.contractId}】`}}</v-expansion-panel-header>
            <v-expansion-panel-content>

              <v-card-text>申请项</v-card-text>
              <v-container class="pa-0">
                <v-card elevation="0" outlined>

                  <!-- 发车申请表格 -->
                  <v-data-table class="elevation-0 mt-0 mb-xs-4 flex-fill d-flex flex-column" :loading="isTableLoading"
                    :headers="headers" :items="[ticket.ticketContent]" hide-default-footer disable-pagination>

                    <template v-slot:item.car-id="{ item }">
                      <v-text-field class="jh-v-input mr-2" filled dense single-line label="车辆编号" v-model="item.carId"
                        readonly>
                      </v-text-field>
                    </template>

                    <template v-slot:item.car-number="{ item }">
                      <v-text-field class="jh-v-input mr-2" filled dense single-line label="车牌号"
                        v-model="item.carNumber" readonly>
                      </v-text-field>
                    </template>

                    <template v-slot:item.current-kilometers="{ item }">
                      <v-text-field class="jh-v-input mr-2" filled dense single-line label="目前公里数"
                        v-model="item.currentKilometers">
                      </v-text-field>
                    </template>

                    <template v-slot:item.dispatch-fuel="{ item }">
                      <v-text-field class="jh-v-input mr-2" filled dense single-line label="目前燃油量"
                        v-model="item.dispatchFuel">
                      </v-text-field>
                    </template>


                  </v-data-table>
                </v-card>
                <!-- <v-btn class="add-btn" @click="doUiAction('addItem')" width="100%" v-if="ticketType==='flow'">添加申请项
                    </v-btn> -->
              </v-container>

              <v-card-text>工单描述</v-card-text>
              <v-textarea class="jh-v-input" dense single-line filled v-model="ticket.ticketDesc" disabled></v-textarea>


            </v-expansion-panel-content>
          </v-card>
        </v-expansion-panel>
      </v-expansion-panels>

    </v-form>
    <!-- 抽屉关闭按钮 -->
    <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn"
      @click="isUpdateDrawerShown = false">
      <v-icon>mdi-close</v-icon>
    </v-btn>
  </v-navigation-drawer>
</template>

<script type="module">
  Vue.component("carActionRequest-handle", {
    template: '#carActionRequest-handle',
    props: {
    },
    data: () => ({
      validationRules: {
        requireRules: [
          v => !!v || '必填',
        ],
        numberRules: [
          v => (!isNaN(v) && parseInt(v) > 0) || '数字必填'
        ]
      },
      constantObj: {},

      isTableLoading: true,
      headers: [
        { text: "车辆编号", value: "car-id", class: 'fixed', cellClass: 'fixed' },
        { text: "车牌号", value: "car-number" },
        { text: "目前公里数", value: "current-kilometers" },
        { text: "目前燃油量", value: "dispatch-fuel" },
      ],

      orderIds: [],
      ticketList: [],
      actionType: '',
      expands: [],

      isUpdateDrawerShown: false,
      createActionData: {},
    }),
    computed: {
      ticketType() {
        const ticket = this.ticketList[0] || {}
        return ticket.ticketType;
      },
      isAllowUpdate(){
        return this.actionType === '处理';
      }
    },
    async created() {
    },
    async mounted() {
    },
    methods: {
      async doUiAction(uiActionId, uiActionData) {
        try {
          switch (uiActionId) {
            case 'startUpdateItem':
              await this.prepareUpdateFormData(uiActionData);
              await this.getTicketData();
              await this.openUpdateDrawer();
              break;
            case 'updateItem':
              await this.prepareCreateValidate();
              await this.confirmCreateItemDialog();
              await this.prepareDoCreateItem();
              await this.doCreateItem();
              await this.closeCreateDrawer();
              break;
            default:
              console.error("[doUiAction] uiActionId not find", { uiActionId });
              break;
          }
        } catch (error) { await window.jhMask.hide(); throw error; }
      },

      // ---------- 初始化数据 uiAction >>>>>>>>>> --------
      async prepareUpdateFormData({ ticketIds = [], actionType, ticketType }) {
        this.ticketIds = ticketIds;
        this.actionType = actionType;
      },
      async getTicketData() {
        this.isTableLoading = true;
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'ticketManagement',
              actionId: 'selectItemList',
              actionData: {},
              whereIn: { ticketId: this.ticketIds },
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;

        this.ticketList = _.map(rows, item => {
          const ticketContent = item.ticketContent ? JSON.parse(item.ticketContent) : JSON.parse(item.ticketContentRequest);
          return {
            ...item,
            ticketContent
          }
        });
        this.expands = _.map(this.ticketList, (item, index) => index);
        this.isTableLoading = false;
      },
      async openUpdateDrawer() {
        this.isUpdateDrawerShown = true;
      },
      // ---------- <<<<<<<<<<< 初始化数据 uiAction ---------

      // ---------- 新增数据 uiAction >>>>>>>>>> --------
      async prepareCreateValidate() {
        if (await this.$refs.createForm.validate()) {
          return true;
        }
        await window.vtoast.fail("请完善表单信息");
        throw new Error("请完善表单信息")
      },
      async confirmCreateItemDialog() {
        if (await window.confirmDialog({ title: "提交", content: "确定提交吗？" }) === false) {
          throw new Error("[confirmCreateFormDialog] 否");
        }
      },
      prepareDoCreateItem() {
        this.createActionData = _.map(this.ticketList, item => {
          return {
            ticketStatus: '完成',
            ticketId: item.ticketId,
            ticketBizId: item.contractId,
            carId: item.ticketContent.carId,
            ticketType: item.ticketType,
            orderId: item.ticketContent.contractId,
            ticketContent: {
              ..._.omit(item, ['getCarTicket', 'returnCarTicket', 'ticketContent']),
            },
            ticketDesc: item.ticketDesc
          };
        })
      },
      async doCreateItem() {
        await window.vtoast.loading("提交数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'ticketManagement',
              actionId: 'handleCarRequestTicket',
              actionData: { dataList: this.createActionData }
            }
          }
        })
        await window.vtoast.success("提交成功");
      },
      async closeCreateDrawer() {
        this.isUpdateDrawerShown = false;
        this.createActionData = null;
        this.$emit("success");
      },
      // ---------- <<<<<<<<<<< 新增数据 uiAction ---------
    }
  })
</script>
<style>
  .jh-v-input .v-messages-outer,
  .jh-v-input .v-text-field__details {
    bottom: -15px !important;
  }
</style>